<template>
    <span v-on:click="toggle()">
        <Button type="primary" v-if="currentValue === trueValue">{{name}}</Button>
        <Button type="ghost" v-else>{{name}}</Button>
    </span>
</template>
<script>
    import Emitter from '../../../node_modules/iview/src/mixins/emitter';
    import {findComponentUpward} from '../../../node_modules/iview/src/utils/assist'

    export default {
        name:'HorizonSwitch',
        mixins:[Emitter],
        props:{
            value:{
                type:[String,Number,Boolean],
                default:false
            },
            trueValue: {
                type: [String, Number, Boolean],
                default: true
            },
            falseValue: {
                type: [String, Number, Boolean],
                default: false
            },
            label: {
                type: [String, Number]
            },
            name:String,
            parentName: {
                type:String,
                default:'SwitchGroup'
            }
        },
        data(){
            return{
                currentValue:this.value,
                group:false,
                parent:findComponentUpward(this,this.parentName)
            }
        },
        mounted(){
            if(this.parent) this.group = true
            if(this.group){
                this.parent.updateValue()
            }else{
                this.updateValue()
            }
        },
        methods:{
            toggle(){
                const checked = this.currentValue === this.trueValue ? this.falseValue : this.trueValue;

                this.$emit('input',checked)
                if(this.group && this.label !== undefined){
                    this.parent.change({
                        value:this.label,
                        label:this.name,
                        checked:checked
                    })
                }
                this.currentValue = checked

                if(!this.group){
                    this.$emit('on-change',value)
                }
            },
            updateValue(){
                this.currentValue = this.value === this.trueValue
            }
        },
        watch:{
            value(val){
                if(val !== this.trueValue && val !== this.falseValue){
                    throw 'Value should be trueValue or falseValue.';
                }
                this.updateValue()
            }
        }
    }
</script>